Problem :
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
Example 1 :
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2 :
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
核心思維 :
程式碼 :
class Solution {
public:
int maxProfit(vector<int>& prices) {
//設置maxprice紀錄最大利潤
int maxprice = 0;
//設置minprice紀錄最低價格
int minprice = prices[0];
//遍歷所有價格
for(int i = 0; i < prices.size(); i++){
//更新minprice為目前的最低價格
minprice = min(minprice, prices[i]);
//更新maxprice為當前價格與minprice之間的利潤
maxprice = max(maxprice, prices[i] - minprice);
}
//回傳最大利潤
return maxprice;
}
};
結論 :
這題的目標是找出最大利潤,透過遍歷確定定價的陣列中可以得到的最大利潤,透過持續更新當前的最低價格,並計算當前價格相對於最低價格的利潤,最後回傳maxprice代表所能獲取的最大利潤。